//
//  ViewController.m
//  25-dispatch
//
//  Created by 殷殷明静 on 16/8/17.
//  Copyright © 2016年 殷明静. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
- (IBAction)btn:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIImageView *secImageView;

- (IBAction)secBtn:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 进程的概念:当用户下达一个执行程序的命令时所启动的东西,比作工厂
    // 线程的概念:线程是进程的执行单位,比作工人
    // 所有UI的操作都放在主线程中
    // 需要开辟线程的耗时操作,图像文字渲染,大数据存储,网络请求
    // NSThread
    NSThread *mainThread = [NSThread currentThread];
    mainThread.name = @"殷明静的屠杀广场";
    NSLog(@"%@",mainThread);
    NSLog(@"%d",[NSThread isMultiThreaded]);
    // 延时sleepUntilDate
    // exit退出线程,不要退出主线程
    // threadPriority优先级
    // 判断当前线程是不是主线程
    [NSThread isMultiThreaded];
    // 判断当前对象是不是主线程
    [[NSThread mainThread] isMainThread];
    // 初始化方法,需要手动管理线程的生命周期
    NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(myThread) object:nil];
    myThread.name = @"我的线程";
    [myThread start];
    
}
- (void)myThread {
    NSLog(@"%s",__FUNCTION__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160804071357748.jpg
// http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160804071401113.jpg
- (IBAction)btn:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160804071357748.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    // 创建子线程1
    [NSThread detachNewThreadWithBlock:^{
        NSThread *sonThread = [NSThread currentThread];
        sonThread.name = @"殷明静小儿子的屠杀广场";
        // 返回主线程去做
        [self performSelectorOnMainThread:@selector(onMainThreadImage:) withObject:data waitUntilDone:YES];
        
        NSLog(@"%@",sonThread);
    }];
    
}
- (void)onMainThreadImage:(id)objc {
    _imageView.image = [UIImage imageWithData:objc];
}
- (IBAction)secBtn:(id)sender {
    // 不关心进程问题,不在乎创建什么样的线程
   
    NSURL *url1 = [NSURL URLWithString:@"http://www.lingyu.me/wp-content/uploads/2016/08/www.lingyu.me_20160804071357748.jpg"];
    NSData *data1 = [NSData dataWithContentsOfURL:url1];

    [self performSelectorInBackground:@selector(secImageViewAction:) withObject:data1];
}
- (void)secImageViewAction:(id)objc{
    // 创建子线程2
    [NSThread detachNewThreadSelector:@selector(newThreadAction:) toTarget:self withObject:objc];
}
- (void)newThreadAction:(id)objc{
    
    NSThread *sonThread = [NSThread currentThread];
    sonThread.name = @"殷明静大儿子的屠杀广场";
    [self performSelectorOnMainThread:@selector(returnToMainThread:) withObject:objc waitUntilDone:YES];
    NSLog(@"%@",sonThread);
    
}
- (void)returnToMainThread:(id)objc {
    _secImageView.image = [UIImage imageWithData:objc];
    
}
@end
